package com.hwpt.chesedemo.data.local.repository

import android.content.Context
import com.hwpt.chesedemo.presentation.component.GameState
import com.hwpt.chesedemo.presentation.component.Player
import com.hwpt.chesedemo.data.local.ChessDatabase
import com.hwpt.chesedemo.data.local.SavedGameLocalDataSource
import com.hwpt.chesedemo.data.local.entity.GameRecordEntity
import com.hwpt.chesedemo.presentation.theme.AppStrings
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class ChessRepositoryImpl @Inject constructor(
    @ApplicationContext private val context: Context
) : ChessRepository {

    // 初始化数据库相关组件
    private val database = ChessDatabase.getInstance(context)
    private val localDataSource = SavedGameLocalDataSource(database.savedGameDao())

    override fun getSavedGames(): Flow<List<GameRecordEntity>> {
        return localDataSource.getAllGames()
    }

    override suspend fun deleteSavedGame(gameId: String) {
        localDataSource.deleteGame(gameId)
    }

    override suspend fun saveGame(state: GameState) {
        val pgnContent = generatePGN(state)
        val gameResult = state.gameResult

        // 获取难度名称
        val difficultyName = if (state.selectedDifficulty != null) {
            getDifficultyDisplayName(state.selectedDifficulty.nameKey)
        } else {
            "Unknown"
        }

        val savedGame = GameRecordEntity(
            id = UUID.randomUUID().toString(),
            pgn = pgnContent,
            playerColor = "WHITE",
            aiDifficulty = difficultyName,
            result = when {
                gameResult?.winner == Player.WHITE -> "玩家获胜"
                gameResult?.winner == Player.BLACK -> "AI获胜"
                else -> "和棋"
            },
            moveCount = state.moveCount,
            createdAt = System.currentTimeMillis(),
            gameDuration = 0
        )

        localDataSource.saveGame(savedGame)
    }

    private fun generatePGN(state: GameState): String {
        val movesText = state.moveHistory.joinToString(" ") { move ->
            buildString {
                append("${move.moveNumber}.")
                if (move.whiteMove != null) {
                    append(" ${move.whiteMove}")
                }
                if (move.blackMove != null) {
                    append(" ${move.blackMove}")
                }
            }
        }.trim()

        val result = when {
            state.gameResult?.winner == Player.WHITE -> "1-0"
            state.gameResult?.winner == Player.BLACK -> "0-1"
            else -> "1/2-1/2"
        }

        return "$movesText $result"
    }

    // 根据难度键名获取显示名称
    private fun getDifficultyDisplayName(nameKey: String): String {
        // 这里需要根据当前语言设置获取对应的难度名称
        // 由于这是一个非Composable环境，我们需要使用默认语言或当前设置的语言
        val strings = AppStrings.getByLanguageCode(getCurrentLanguageCode())
        return AppStrings.getDifficultyName(strings, nameKey)
    }

    // 获取当前语言代码
    private fun getCurrentLanguageCode(): String {
        // 这里应该从SharedPreferences或其他存储中获取用户设置的语言
        // 暂时返回默认语言（中文）
        return "zh"

        // 如果集成了LanguageManager，可以这样：
        // return LanguageManager.currentLanguageCode
    }
}